package com.ruyuan2020.im.code.l618;

import java.util.concurrent.DelayQueue;

public class DelayQueueExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建 DelayQueue
        DelayQueue<DelayedTask> delayQueue = new DelayQueue<>();

        // 添加延迟任务到队列
        delayQueue.put(new DelayedTask(3000, "Task 1")); // 延迟 3 秒
        delayQueue.put(new DelayedTask(1000, "Task 2")); // 延迟 1 秒
        delayQueue.put(new DelayedTask(2000, "Task 3")); // 延迟 2 秒

        // 启动一个线程来处理延迟任务
        new Thread(() -> {
            try {
                while (true) {
                    // 从队列中取出任务
                    DelayedTask task = delayQueue.take();
                    System.out.println("Executed: " + task.getTaskName() + " at " + System.currentTimeMillis());
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();

        // 主线程等待一段时间，以便查看任务的执行
        Thread.sleep(5000);
    }
}
